package com.xuecheng.media.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.spring.util.ObjectUtils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class VodTemplate {
    @Autowired
    private AliyunProperties prop;

    private DefaultAcsClient client;

    //初始化client
    @PostConstruct
    public void init(){
        DefaultProfile profile = DefaultProfile.getProfile(
                prop.getRegion(),
                prop.getAccessKeyId(),
                prop.getAccessKeySecret());
        client=new DefaultAcsClient(profile);
    }

    /*
    * 获取视频上传地址和凭证
    * @param fileTitle 流媒体文件的显示名称
    * @param fileName 流媒体文件的原始名称
    * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
    * */
    public CreateUploadVideoResponse createUploadVideo(String fileTitle,String fileName) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle(fileTitle);
        request.setFileName(fileName);
        return client.getAcsResponse(request);
    }

    /*
    * 刷新视频上传凭证
    * @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
    * */
    public RefreshUploadVideoResponse refreshUploadVideo(String videoId) throws ClientException {
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /*
    * 获得媒资播放请求对象
    * */
    public GetPlayInfoResponse getplayInfo(String videoId) throws ClientException {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /*
    * 删除视频
    * @param videoIds 流媒体文件的fileId值
    * @param DeleteVideoResponse 删除视频响应数据
    * @throws Exception
    * */
    public void deleteVideo(String... videoIds) throws ClientException {
        DeleteVideoRequest request = new DeleteVideoRequest();
        if(ObjectUtil.isEmpty(videoIds)){
            return;
        }
        //支持多个文件视频ID，多个用逗号分离
        String videoIdsStr = String.join(",", videoIds);
        request.setVideoIds(videoIdsStr);
        client.getAcsResponse(request);
    }
}
